package com.zking.db;


import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;


public class DBPool {
    //数据源（数据库）
	private DataSource dataSource=null;
	
	private DBPool() {
		//创建数据源
		try {
			dataSource=DruidDataSourceFactory.createDataSource(getProperties("db.properties"));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	private static DBPool pool=null;
	//获取实例
	public static DBPool getInstance() {
		if(pool==null) {
			pool=new DBPool();
		}
		return pool;
	}
	//通过数据源获取连接
	public Connection getConn() throws SQLException {
		return dataSource.getConnection();
	}
	//获取数据源
	public DataSource getDataSource() {
		return dataSource;
	}
	public Properties getProperties(String prosPath) {
		//创建一个properties对象
		Properties pros=new Properties();
		//获取源文件的字节输入流
		InputStream in=null;
		try {
			//class文件所在的位置目录
			String path=DBPool.class.getResource("/").getPath();
			path=URLDecoder.decode(path,"utf-8");
			in=new FileInputStream(path+"/"+prosPath);
			pros.load(in);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return pros;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DBPool dbpool=new DBPool();
		try {
			System.out.println(dbpool.getConn());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

